classdef NIBORyieldCurve < handle
    properties ( SetAccess = private )
        yieldCurveMap = containers.Map();
        maturities = [1 7 14 30 60 90 180 270 360] / 360;
    end
    
    methods
        %%
        function obj = NIBORyieldCurve()
            %Get data from bank of Norway web page
            link = 'http://www.norges-bank.no/templates/article____55480.aspx';
            data_string = urlread( link );
            data_string = data_string( strfind( data_string,'<!-- START INKLUDERINGSFILER MM-->' ):...
                strfind( data_string,'<!-- END INKLUDERINGSFILER MM -->' ) );

            %Extract yields and create map
            row_start_ind = strfind( data_string, '<TR' );
            row_end_ind = strfind( data_string, '</TR>' );
            yields = zeros( 1, 9 );
            num_str = '3,45';
            for i = 2:length( row_start_ind )
                line = data_string( row_start_ind(i):row_end_ind(i) );
                td_start = strfind( line, '<TD>' );
                td_end =  strfind( line, '</TD>' );
                
                date = line( td_start(1)+4:td_end(1)-1 );
                for j = 2:length( td_start )
                    num_str = line( td_start(j)+4:td_end(j)-1 );
                    yields( j-1 ) = str2double(strrep( num_str, ',' , '' ));
                end
                yields = yields / 10000;
                obj.yieldCurveMap( datestr(datenum( date )) ) = yields;
            end
        end
        
        
        
        %%
        function spotrate = getHistSpotRate( obj, T, date )
           rates = obj.yieldCurveMap( date );
            
           spotrate = spline( obj.maturities, rates, T );
        end
        
        
        
        %%
        function spotrate = getSpotRate( obj, T )
           i = 0;
           while ~obj.yieldCurveMap.isKey( datestr( today-i ) )
               i = i+1;
           end
           rates = obj.yieldCurveMap( datestr( today-i ) );
            
           spotrate = spline( obj.maturities, rates, T );
        end
    end
    
end